/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Block;

import DAO.AccountDAO;
import DAO.AccountLevelDAO;
import DAO.ConnectDatabase;
import DAO.DepartmentDAO;
import Helper.AccountHelper;
import Helper.AccountLevelHelper;
import Helper.DepartmentHelper;
import Model.AccountModel;
import Model.DepartmentModel;
import common.CalendarFormat;
import common.Constant;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author KIENLT
 */
public class Department extends javax.swing.JPanel {

    ArrayList<DepartmentHelper> arrDepartment;
    ArrayList<DepartmentHelper> arrDepartmentList;
    DepartmentHelper departmentData;
    ResultSet rs = null;

    /**
     * Creates new form Department
     */
    public Department() {
        initComponents();
        fillAllDepartment();
        changeLanguage();
    }

     private void changeLanguage() {
        if(Constant.getLanguage() == 0){
            Constant.initBundle();
            getLanguage();
        }else{
            Constant.initBundle();
            getLanguage();
        }
    }
    
    private void getLanguage() {
        lblDepId.setText(Constant.getBundle().getString("departmentId"));
        lblDepName.setText(Constant.getBundle().getString("departmentName"));
  //      lblDepStatus.setText(Constant.getBundle().getString("departmentStatus"));
        btnUpdate.setText(Constant.getBundle().getString("update"));
        btnDelete.setText(Constant.getBundle().getString("delete"));
        btnAdd.setText(Constant.getBundle().getString("add"));  
    }
    // Hiển thị tất cả Department
    private void fillAllDepartment() {
        try {
            arrDepartment = DepartmentDAO.fillAll(ConnectDatabase.ConnectionDatabase());
            arrDepartmentList = new ArrayList<DepartmentHelper>();

            for (DepartmentHelper item : arrDepartment) {
                arrDepartmentList.add(item);
            }

            tblDepartment.setModel(new DepartmentModel(arrDepartmentList));

            DefaultTableColumnModel model = (DefaultTableColumnModel) tblDepartment.getColumnModel();
            TableColumn tblCol = model.getColumn(1);
            tblCol.setPreferredWidth(250);
        } catch (Exception ex) {
            try {
                ConnectDatabase.CloseDB(ConnectDatabase.ConnectionDatabase());
            } catch (Exception ex1) {
                Logger.getLogger(Department.class.getName()).log(Level.SEVERE, null, ex1);
            }
            ex.printStackTrace();
        }
        if (arrDepartmentList.size() > 0) {
            tblDepartment.getSelectionModel().setSelectionInterval(0, 0);
            fillOneDepartment();
        }

        tblDepartment.getSelectionModel().addListSelectionListener(
                new ListSelectionListener() {

                    @Override
                    public void valueChanged(ListSelectionEvent e) {

                        boolean adjust = e.getValueIsAdjusting();
                        if (adjust) {
                            fillOneDepartment();
                        }
                    }
                });
    }
    // Hiển thị thong tin department

    private void fillOneDepartment() {
        try {
            departmentData = new DepartmentHelper();
            int row = tblDepartment.getSelectedRow();
            departmentData.setDepartmentID(tblDepartment.getValueAt(row, 0).toString());
            rs = DepartmentDAO.FillOne(ConnectDatabase.ConnectionDatabase(), departmentData);
            if (rs.next()) {
                txtDepID.setText(rs.getString("DepartmentId"));
                txtDepName.setText(rs.getString("DepartmentName"));
   //             txtStatus.setText(rs.getString("Status"));
  
            }
        } catch (Exception ex) {
            try {
                ConnectDatabase.CloseDB(rs);
                ConnectDatabase.CloseDB(ConnectDatabase.ConnectionDatabase());
            } catch (Exception ex1) {
                Logger.getLogger(Department.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblDepartment = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        lblDepId = new javax.swing.JLabel();
        lblDepName = new javax.swing.JLabel();
        txtDepID = new javax.swing.JTextField();
        txtDepName = new javax.swing.JTextField();
        btnAdd = new javax.swing.JButton();
        btnUpdate = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();

        setPreferredSize(new java.awt.Dimension(800, 452));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Department", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N

        tblDepartment.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tblDepartment);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Department Infomation", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N

        lblDepId.setText("Department ID");

        lblDepName.setText("Department Name");

        txtDepID.setEnabled(false);

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/img_x16/add2.png"))); // NOI18N
        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnUpdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/img_x16/update.png"))); // NOI18N
        btnUpdate.setText("Update");
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/img_x16/delete2.png"))); // NOI18N
        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(132, 132, 132)
                        .addComponent(btnAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnUpdate)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDelete)
                        .addGap(14, 140, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblDepId, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txtDepID, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblDepName, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDepName)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDepId)
                    .addComponent(txtDepID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDepName)
                    .addComponent(txtDepName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd)
                    .addComponent(btnUpdate)
                    .addComponent(btnDelete))
                .addContainerGap(278, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        try {
            // TODO add your handling code here:
            DepartmentHelper Department = new DepartmentHelper();
            int row = tblDepartment.getSelectedRow();
            Department.setDepartmentID(tblDepartment.getValueAt(row, 0).toString());
            Department.setDepartmentName(txtDepName.getText());
  //          Department.setDepartmentStatus(txtStatus.getText());

            if (!DepartmentDAO.checkDepartmentName(ConnectDatabase.ConnectionDatabase(), Department)) {
                int query = DepartmentDAO.Insert(ConnectDatabase.ConnectionDatabase(), Department);
                if (query > 0) {
                    JOptionPane.showMessageDialog(this, "Insert Success.", "Message", JOptionPane.INFORMATION_MESSAGE);
                    fillAllDepartment();
                } else {
                    JOptionPane.showMessageDialog(this, "Insert Fail.", "Error", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(this, "Name is exists.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            Logger.getLogger(Department.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_btnAddActionPerformed

    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        try {
            // TODO add your handling code here:

            DepartmentHelper dep = new DepartmentHelper();
            dep.setDepartmentID(txtDepID.getText());
            dep.setDepartmentName(txtDepName.getText());
//            dep.setDepartmentStatus(txtStatus.getText());
            if (!DepartmentDAO.checkDepartmentName(ConnectDatabase.ConnectionDatabase(), dep)) {
                int query = DepartmentDAO.UpdateDep(ConnectDatabase.ConnectionDatabase(), dep);
                if (query > 0) {
                    JOptionPane.showMessageDialog(this, "Update Success.", "Message", JOptionPane.INFORMATION_MESSAGE);
                    fillAllDepartment();
                } else {
                    JOptionPane.showMessageDialog(this, "Update Fail.", "Error", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(this, "Name is exists.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            Logger.getLogger(Department.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_btnUpdateActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        //  removeTableDepartment();
        try {
            DepartmentHelper dep = new DepartmentHelper();
            dep.setDepartmentID(txtDepID.getText());
            int option = JOptionPane.showConfirmDialog(this, "You are sure delete?", "Message", JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.YES_OPTION) {
                int query = DepartmentDAO.Delete(ConnectDatabase.ConnectionDatabase(), dep);

                if (query > 0) {
                    JOptionPane.showMessageDialog(this, "Delete Success.", "Message", JOptionPane.INFORMATION_MESSAGE);
                    fillAllDepartment();
                } else {
                    JOptionPane.showMessageDialog(this, "Delete Fail.", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(Department.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void deleteDep() {
        // TODO add your handling code here:
        try {
            departmentData = new DepartmentHelper();
            int[] rows = tblDepartment.getSelectedRows();
            for (int i = 0; i < rows.length; i++) {
                System.out.println(tblDepartment.getValueAt(rows[i], 0));
                String check = String.valueOf(tblDepartment.getValueAt(rows[i], 0));
                if (check.equals("true")) {
                    departmentData.setDepartmentID(String.valueOf(tblDepartment.getValueAt(rows[i], 1)));
                    DepartmentDAO.Delete(ConnectDatabase.ConnectionDatabase(), departmentData);
                }
            }
        } catch (Exception ex) {
            try {
                ConnectDatabase.CloseDB(ConnectDatabase.ConnectionDatabase());
            } catch (Exception ex1) {
                Logger.getLogger(Department.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
    }

    private void removeTableDepartment() {
        // TODO add your handling code here:
        int[] rows = tblDepartment.getSelectedRows();
        for (int i = rows.length - 1; i >= 0; i--) {
            DepartmentModel depModel = (DepartmentModel) tblDepartment.getModel();
            if (String.valueOf(tblDepartment.getValueAt(rows[i], 0)).equals("true")) {
                int option = JOptionPane.showConfirmDialog(this, "You are sure delete?", "Message", JOptionPane.YES_NO_OPTION);
                if (option == JOptionPane.YES_OPTION) {
                    deleteDep();
                    depModel.deleteRow(rows[i]);
                }
            }
        }
}//GEN-LAST:event_btnDeleteActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblDepId;
    private javax.swing.JLabel lblDepName;
    private javax.swing.JTable tblDepartment;
    private javax.swing.JTextField txtDepID;
    private javax.swing.JTextField txtDepName;
    // End of variables declaration//GEN-END:variables
}
